/**
 * api请求模块化处理
 */
const URLS = {
  hotUrl: 'https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items',
  latestUrl: 'https://m.douban.com/rexxar/api/v2/subject_collection/movie_latest/items',
  freeUrl: 'https://m.douban.com/rexxar/api/v2/subject_collection/movie_free_stream/items',
  detailUrl: 'https://m.douban.com/rexxar/api/v2/movie/'
}

const showError = () => {
  wx.showToast({
    title: '数据加载失败',
    image: '/imgs/error.png'
  })
}

const loadHotFilms = function (params={}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: URLS.hotUrl,
      data: params,
      success: resolve,
      fail: reject
    })
  }).then(res => {
    if (res.statusCode === 200) {
      res.data.method = 'loadHotFilms'
      return res.data
    }
  })
  
}

const loadLatestFilms = function (params={}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: URLS.latestUrl,
      data: params,
      success: resolve,
      fail: reject
    })
  }).then(res => {
    if (res.statusCode === 200) {
      res.data.method = 'loadLatestFilms'
      return res.data
    }
  })
}

const loadFreeFilms = function (params={}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: URLS.freeUrl,
      data: params,
      success: resolve,
      fail: reject
    })
  }).then(res => {
    if (res.statusCode === 200) {
      res.data.method = 'loadFreeFilms'
      return res.data
    }
  })
}

const loadFilmByFilmId = function (filmId) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: URLS.detailUrl + filmId,
      success: resolve,
      fail: reject
    })
  }).then (res => {
    if (res.statusCode === 200) {
      return res.data
    }
  })
}

const loadCommentByFilmId = function (filmId, params={}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: URLS.detailUrl + filmId + '/interests',
      data: params,
      success: resolve,
      fail: reject
    })
  }).then (res => {
    if (res.statusCode === 200) {
      return res.data
    }
  })
}


module.exports = {
  showError,
  loadHotFilms,
  loadLatestFilms,
  loadFreeFilms,
  loadFilmByFilmId,
  loadCommentByFilmId
}